package com.simen.hellobytes.encode;

import java.io.IOException;
import java.io.StringReader;

public class UnicodeUtil {

    public static String decode(String source) throws IOException {
        StringReader sr = new StringReader(source);
        UnicodeUnescapeReader uur = new UnicodeUnescapeReader(sr);
        StringBuffer buf = new StringBuffer();

        int c = 0;
        while ((c = uur.read()) != -1) {
            buf.append((char) c);
        }

        return buf.toString();
    }

    public static String encode(String str) {
        StringBuffer buf = new StringBuffer();
        char[] utfBytes = str.toCharArray();
        for (int i = 0; i < utfBytes.length; i++) {
            if (utfBytes[i] <= 0x7f) {
                buf.append(utfBytes[i]);
            } else {
                String hexB = Integer.toHexString(utfBytes[i]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                buf.append("\\u" + hexB);
            }
        }
        return buf.toString();
    }

}
